package org.hot100_2;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class leetcode347 {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for (int num:nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }

        PriorityQueue<int[]> priorityQueue = new PriorityQueue<>((arr1,arr2)->arr1[1]-arr2[1]);

        for (Map.Entry<Integer,Integer> entry:map.entrySet()) {
                if (priorityQueue.size()<k){
                    priorityQueue.add(new int[]{entry.getKey(),entry.getValue()});
                }else {
                    if (entry.getValue()>priorityQueue.peek()[1]){
                        priorityQueue.poll();
                        priorityQueue.add(new int[]{entry.getKey(),entry.getValue()});
                    }
                }
        }


        int [] res = new int[k];

        for (int i = 0; i < k; i++) {
            res[i]=priorityQueue.poll()[0];
        }

        return res;
    }
}
